import {createSlice, PayloadAction} from "@reduxjs/toolkit";

export interface UserInfoI {
    name: string
    id: string
}

export interface UserState {
    // 是否登录
    isLogin: boolean;
    // 用户信息
    userInfo: UserInfoI;
}

const initialState: UserState = {
    // 基于token判断是否登录
    isLogin: window.localStorage.getItem("token") !== null,
    userInfo: JSON.parse(window.localStorage.getItem("userInfo") ?? "{}"),
};

export const userSlice = createSlice({
    name: "user",
    initialState,
    reducers: {
        login: (_, action: PayloadAction<{
            userInfo: UserInfoI,
            token: string,
            from: string | null
        }>) => {
            window.localStorage.setItem("userInfo", JSON.stringify(action.payload.userInfo))
            window.localStorage.setItem("token",action.payload.token)
            if (action.payload.from) {
                window.location.href = action.payload.from
            }else {
                window.location.href = "/admin/projectCenter/dashboard"
            }
        },
        logout: (state) => {
            localStorage.removeItem("token");
            window.localStorage.removeItem("token")
            state.isLogin = false;
        },
    },
});

export const {login, logout} = userSlice.actions;

export default userSlice.reducer;
